<?php

namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Helpers\Helper;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildManage;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use Psr\EventDispatcher\EventDispatcherInterface;
use App\Event\InviteEvent;

/**
 * 验证码检测，并直接登录或者注册
 */
class CaptchaCheckService extends AuthBaseService
{
    public function handle()
    {
        $phone = $this->request->input('phone');
        $captcha = $this->request->input('captcha');
        $inviteCode = $this->request->input('invite_code', '');
        //公会ID
        $guildId = $this->request->input('guild_id', '');

        //检测验证码
        $check = Helper::checkCaptcha($phone, $captcha);
        log_info(__CLASS__ . "==Phone:{$phone}==Captcha:{$captcha}==White:" . ($this->checkWhitePhone($phone) ? 'True' : 'False') . "==Check:" . ($check ? 'True' : 'False'));
        if (
            !check_dev_env()
            && !$check
            && !$this->checkWhitePhone($phone)
            && $captcha != env('WHITE_PASS_CAPTCHA', '8039')
        ) {
            return $this->setError(ErrorCode::CAPTCHA_ERR, '验证码错误');
        }

        //手机号登录（注册）
        $ret = $this->authPhoneLogin($phone);
        //异常
        if (!isset($ret['user_info'])) return $ret;

        $ret['guild_binded'] = 0;
        $userId = $ret['user_info']['user_id'];

        if (!isset($ret['user_info']['user_profile_id'])) {
            $profileId = UserProfile::makeProfileUid($userId);
            $upInfo = ['user_id' => $userId, 'user_profile_id' => $profileId];
            //输入了合法的邀请码，且非公会主播
            if (
                $inviteCode &&
                ($inviterProfile = UserProfile::getInfoByProfileId($inviteCode)) &&
                !GuildHost::checkInGuild($userId)
            ) {
                $upInfo['invite_code'] = $inviteCode;
                make(EventDispatcherInterface::class)->dispatch(new InviteEvent($inviterProfile->user_id, $userId, $inviterProfile));
            }
            UserProfile::updateOrCreate(['user_id' => $userId], $upInfo);
        } else {
            $profileId = $ret['user_info']['user_profile_id'];
        }

        //绑定公会ID
        if ($guildId) {
            //存在被邀请绑定关系
            if (UserProfile::getInviteCode($userId)) {
                return $this->setError(ErrorCode::GUILD_CANT_INVITED, '该账号有被他人邀请注册，请联系客服微信：' . config('busi.kefu_wechat'));
            }
            //判断是否是注册
            if($ret['fix_profile'] != 1){
                return $this->setError(ErrorCode::GUILD_CANT_INVITED_FAILED, '你的账号已注册，暂无法绑定');
            }
            $guildInfo = GuildManage::getInfoByGuildId($guildId);
            $vrf = UserProfilePersonal::isRealnameVerified(UserProfilePersonal::getProfile($userId));
            $result = GuildHost::bindHost($userId, $guildInfo['id'], $vrf, $profileId);
            if (false === $result) $ret['guild_binded'] = 1;
        }

        //是否显示邀请码
        $ret['show_invitecode'] = env('SHOW_INVITECODE', 1);
        log_info(__CLASS__ . "==" . json_encode($ret));
        return $ret;
    }
}
